package com.wangyb.wework.service.agent;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.page.PagePlus;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.PageUtils;
import com.wangyb.wework.bo.WwAgentEditBo;
import com.wangyb.wework.bo.WwAgentQueryBo;
import com.wangyb.wework.entity.agent.WwAgent;
import com.wangyb.wework.exception.CommonException;
import com.wangyb.wework.mapper.agent.WwAgentMapper;
import com.wangyb.wework.vo.WwAgentVo;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 企业应用Service业务层处理
 *
 * @author wangyb
 * @date 2021-07-21
 */
@Service
public class WwAgentServiceImpl extends ServiceImpl<WwAgentMapper, WwAgent> implements IWwAgentService {

	@Override
	public WwAgentVo queryById(Long id){
		return getVoById(id, WwAgentVo.class);
	}

	@Override
	public TableDataInfo<WwAgentVo> queryPageList(WwAgentQueryBo bo) {
		PagePlus<WwAgent, WwAgentVo> result = pageVo(PageUtils.buildPagePlus(), buildQueryWrapper(bo), WwAgentVo.class);
		return PageUtils.buildDataInfo(result);
	}

	@Override
	public List<WwAgentVo> queryList(WwAgentQueryBo bo) {
		return listVo(buildQueryWrapper(bo), WwAgentVo.class);
	}

	private LambdaQueryWrapper<WwAgent> buildQueryWrapper(WwAgentQueryBo bo) {
		Map<String, Object> params = bo.getParams();
		LambdaQueryWrapper<WwAgent> lqw = Wrappers.lambdaQuery();
		return lqw;
	}

	@Override
	public Boolean insertByAddBo(WwAgentEditBo bo) {
		Long corpId = 1L;
		WwAgent add = BeanUtil.toBean(bo, WwAgent.class);
		add.setCorpId(corpId);
		validEntityBeforeSave(add);
		return save(add);
	}

	@Override
	public Boolean updateByEditBo(WwAgentEditBo bo) {
		Long corpId = 1L;
		WwAgent update = BeanUtil.toBean(bo, WwAgent.class);
		update.setCorpId(corpId);
		validEntityBeforeSave(update);
		return updateById(update);
	}

	/**
	 * 保存前的数据校验
	 *
	 * @param entity 实体类数据
	 */
	private void validEntityBeforeSave(WwAgent entity){
		//TODO 做一些数据校验,如唯一约束
	}

	@Override
	public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
		if(isValid){
			//TODO 做一些业务上的校验,判断是否需要校验
		}
		return removeByIds(ids);
	}
	@Override
	public String getWxAgentId(Long id){
		WwAgentVo agent = this.queryById(id);
		return agent.getWxAgentId();
	}
	@Override
	public WwAgent getDefaultAgent(Long corpId){
		WwAgent agent = this.lambdaQuery().eq(WwAgent::getCorpId, corpId).list().get(0);
		if(agent != null){
			return agent;
		}else{
			throw new CommonException("当前企业未添加企业应用，请在企业微信后台添加企业应用");
		}
	}
}
